<template>
  <div class="user-space-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchSpaceVisible" inline :model="searchSpaceFrom" ref="searchSpaceForm" @keyup.enter.native="searchSpaceHandle()">
        <el-form-item prop="word" label="空间名称">
          <el-input v-model="searchSpaceFrom.word" @clear="getSpaceList" clearable placeholder="请输入空间名称" ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchSpaceHandle" type="primary" icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetSpacePageHandle" plain icon="el-icon-refresh-right"
                     class="reset-menu">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="s-tool">
      <el-button :disabled="dataLoad" @click="openSpaceDialogHandle(undefined, false)"
                 type="primary" size="mini" plain icon="el-icon-plus"
                 class="add-menu">添加空间</el-button>
      <el-button :disabled="dataLoad || spaceTableSelected.length === 0" @click="deleteSpaceHandle(true, undefined)"
                 type="danger" size="mini" plain icon="el-icon-delete"
                 class="reset-menu">删除空间</el-button>

      <right-tool-bar :search-visible="searchSpaceVisible"
                      @toggle-search="toggleSearch" @refresh-table="getSpaceList" />
    </div>

    <el-table
      v-loading="dataLoad"
      :data="spaceList"
      :default-sort = "{ prop: searchSpaceFrom.field, order: searchSpaceFrom.order}"
      @sort-change="sortChangeHandle"
      @selection-change="selectionChangeHandle"
      ref="spaceTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="name" header-align="center" align="center" label="名字"></el-table-column>
      <el-table-column prop="sort" sortable header-align="center" align="center" label="排序等级"></el-table-column>
      <el-table-column prop="createTime" sortable header-align="center" align="center" label="创建时间"></el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template v-slot="scope">
          <el-button type="text" size="small" @click="openSpaceDialogHandle(scope.row.spaceId, true)">修改</el-button>
          <el-button type="text" size="small" @click="deleteSpaceHandle(false, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页插件 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalNum"
      :disabled="dataLoad"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <space-save-update :dialog-visible="spaceDialog" ref="spaceDialog"
                       @close-space-dialog="closeSpaceDialogHandle"/>
  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar'
  import SpaceSaveUpdate from "@/components/user/space/save-update";

  export default {
    components: { RightToolBar, SpaceSaveUpdate },
    layout: 'admin',
    name: "admin-user-space",
    data() {
      return {
        // 用户空间列表
        spaceList: [],
        // 用户空间表格被选中的‘行’数据
        spaceTableSelected: [],
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 空间检索是否显示
        searchSpaceVisible: true,
        // 空间检索表单对象
        searchSpaceFrom: {
          word: '',           // 空间检索内容
          field: 'sort',      // 排序字段
          order: 'ascending'  // 排序方式
        },
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 10,
        // 当前博客数量
        totalNum: 0,
        // 用户弹出框是否显示
        spaceDialog: false,
      }
    },
    // asyncData({ app, params, query}) {
    //   return app.$axios.$post('/blog/space/list', { page: 1, limit: 10, field: 'sort', order: 'ascending' })
    //     .then(data => {
    //       return {
    //         spaceList: data.page.list,
    //         totalNum: data.page.totalNum
    //       }
    //     })
    //     .catch(() => {})
    // },
    created() {
      if (process.client) {

        this.getSpaceList()
      }
    },
    methods: {
      // 用户空间检索事件
      searchSpaceHandle() {
        if (this.searchSpaceFrom.word === '') {
          return
        }
        this.getSpaceList()
      },
      // 用户检索 显示/隐藏 事件
      toggleSearch() {
        this.searchSpaceVisible = !this.searchSpaceVisible
      },
      // 获取用户数据列表事件
      getSpaceList() {
        let obj = {
          word: this.searchSpaceFrom.word,
          field: this.searchSpaceFrom.field,
          order: this.searchSpaceFrom.order,
          page: this.pageIndex,
          limit: this.pageSize
        }
        // 表格数据加载
        this.dataLoad = true
        this.$axios.$post('/blog/space/list', obj)
          .then(({ data:page }) => {
            this.spaceList = page.list
            this.totalNum = page.totalNum
          })
          .catch(() => {})
          .finally(() => {
            // 表格加载结束
            this.dataLoad = false
          })
      },
      // 每页显示个数变化事件
      sizeChangeHandle(size) {
        this.pageIndex = 1
        this.pageSize = size
        this.getSpaceList()
      },
      // '点击特定页码'、'上一页'、'下一页'操作事件
      currentChangeHandle(index) {
        if (this.pageIndex === index) {
          return
        }
        this.pageIndex = index
        this.getSpaceList()
      },
      // 表格选择字段排序事件
      sortChangeHandle( { prop, order } ) {

        if (!order) {   // 第三次点击同一个排序字段，恢复默认排序
          this.searchSpaceFrom.field = 'sort'
          this.searchSpaceFrom.order = 'ascending' // descending
        } else {
          this.searchSpaceFrom.field = prop
          this.searchSpaceFrom.order = order
        }

        this.getSpaceList()
      },
      // 用户表格行被选中事件
      selectionChangeHandle(data) {
        this.spaceTableSelected = data
      },
      /**
       * 删除空间事件
       * @param optType 操作类型[false-单个删除 true-批量删除]
       * @param space 空间对象（只有单个删除时，该参数才有值）
       */
      deleteSpaceHandle(optType, space) {
        let spaceIds = []    // 所有要删除的用户id
        let spaceName = "["  // 所有要删除的用户名字

        if (optType) {
          this.spaceTableSelected.forEach(space => {
            spaceIds.push(space.spaceId)
            spaceName += space.name + ','
          })
          spaceName = spaceName.substring(0, spaceName.length - 1) // 去掉最后一个‘逗号’
        } else {
          spaceIds.push(space.spaceId)
          spaceName += space.name
        }
        spaceName += ']'

        this.$refs.spaceTable.clearSelection()   // 清空表格选中行

        this.$confirm(`确定删除${spaceName}用户空间吗?`, '空间删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          this.$axios.$post('/blog/space/delete', spaceIds)
            .then(() => {

              this.$notify({
                title: '删除空间成功',
                type: 'success',
                message: `${spaceName}用户空间删除成功`,
                offset: 100,
                duration: 2000
              });

              this.getSpaceList()      // 重新获取空间列表

            })
            .catch(() => {})

        }).catch(() => {})
      },
      // 打开用户操作弹出框事件
      openSpaceDialogHandle(spaceId, optType) {
        this.spaceDialog = true

        this.$nextTick(() => {
          this.$refs.spaceDialog.initSpaceDialog(spaceId, optType)
        })
      },
      // 关闭用户操作弹出框事件
      closeSpaceDialogHandle(bool) {
        this.spaceDialog = false

        if (bool) {
          this.getSpaceList()

          if (this.spaceTableSelected.length > 0) {  // 如果选中行不为空
            this.$refs.spceTable.clearSelection()   // 清空表格选中行
          }
        }
      },
      // 重置页面事件
      resetSpacePageHandle() {
        if (this.searchSpaceFrom.word === '' && this.pageIndex === 1 && this.pageSize === 10) {
          return
        }

        this.$refs['searchSpaceForm'].resetFields()    // 重置角色查询表单
        this.pageIndex = 1
        this.pageSize = 10

        this.getSpaceList()
      }
    }
  }
</script>

<!--
  css字符对应
  u -> user
  s -> space
-->
<style scoped>
  .user-space-page .s-tool {
    margin-bottom: 7px;
  }
  .user-space-page .paging {
    float: right;
    margin: 7px;
  }
</style>
